package com.jackrain.nea.fc.cp.service;

import com.alibaba.dubbo.config.annotation.Service;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.parser.Feature;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.jackrain.nea.config.Resources;
import com.jackrain.nea.exception.NDSException;
import com.jackrain.nea.fc.cp.api.WmsCStoreQueryCmd;
import com.jackrain.nea.fc.cp.mapper.WmsCStoreMapper;
import com.jackrain.nea.sys.CommandAdapter;
import com.jackrain.nea.util.ApplicationContextHandle;
import com.jackrain.nea.util.ValueHolder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * @author xuxinshuai
 * @date 2018/05/05
 */
@Slf4j
@Component
@Service(protocol = "dubbo", validation = "true", version = "1.0", group = "cp")
public class WmsCStoreQueryCmdImpl extends CommandAdapter implements WmsCStoreQueryCmd {

    @Override
    public ValueHolder execute(HashMap map) throws NDSException {

        ValueHolder vh = new ValueHolder();
        WmsCStoreMapper wmsCStoreMapper = ApplicationContextHandle.getBean(WmsCStoreMapper.class);
        JSONObject param = JSON.parseObject(JSON.toJSONStringWithDateFormat(map.get("param"), "yyyy-MM-dd HH:mm:ss", SerializerFeature.WriteMapNullValue), Feature.OrderedField);
        if (null == param || param.size() == 0 || param.getJSONArray("IDS").size() <= 0) {
            throw new NDSException("参数格式错误！");
        }
        log.info("WmsCStoreQueryCmdImpl--param-->{}",param);
//        log.debug("----------店仓WMS查询参数----------" + param);
        List<HashMap> mapList = new ArrayList<>();

        Object[] list = (Object[])  param.getJSONArray("IDS").toArray();
        StringBuilder sb = new StringBuilder();
        for (Object num : list) {
            sb.append(num).append(",");
        }
        sb.deleteCharAt(sb.length() - 1);

//       System.out.print("HHHHHHHH>>>>>>"+sb.toString());

        mapList = wmsCStoreMapper.selectwmsStoresql(sb.toString());

        JSONArray jsonArray = listToJsonarray(mapList);

        vh.put("data", jsonArray);
        vh.put("code", 0);
        vh.put("message", Resources.getMessage("成功"));
        return vh;
    }

    /**
     * list转jsonarray
     *
     * @param mapList
     * @return jsonArray
     */
    public JSONArray listToJsonarray(List<HashMap> mapList) {
        JSONArray jsonArray = new JSONArray();
        for (int i = 0; i < mapList.size(); i++) {
            HashMap map = (HashMap) mapList.get(i);
            JSONObject jsonObject = new JSONObject(map);
            JSONObject param = JSON.parseObject(JSON.toJSONStringWithDateFormat(jsonObject, "yyyy-MM-dd HH:mm:ss", SerializerFeature.WriteMapNullValue), Feature.OrderedField);
            jsonArray.add(param);
        }
        return jsonArray;
    }

}
